package cn.zzm.config;


import cn.zzm.support.activeMQ.QueueListener;
import cn.zzm.support.activeMQ.TopicListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;


/**
 * @program: study
 * @description:activeMQ配置类 与spring整合 不适用springboot自动装配
 * @author: 周昭名
 * @create: 2019-04-10 10:26
 **/
@Configuration
public class ActiveMQConfig {
    @Value("${mq.userName}")
    private String userName;
    @Value("${mq.password}")
    private String password;
    @Value("${mq.brokerUrl}")
    private String brokerUrl;

    @Bean
    public ConnectionFactory connectionFactory(){
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName,password,brokerUrl);
        return connectionFactory;
    }

    @Bean
    public CachingConnectionFactory cachingConnectionFactory(){
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory());
        cachingConnectionFactory.setSessionCacheSize(100);
        return cachingConnectionFactory;
    }


    @Bean
    public DefaultMessageListenerContainer queueMsgListenerContainer() {
        //创建监听queue的Listener
        Destination queue = new ActiveMQQueue("helloActiveMQSpring");
        DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
        dmlc.setConnectionFactory(cachingConnectionFactory());
        dmlc.setDestination(queue);
        dmlc.setMessageListener(new QueueListener());
        return dmlc;
    }

    @Bean
    public DefaultMessageListenerContainer topicMsgListenerContainer() {
        //创建监听queue的Listener
        Destination topic = new ActiveMQTopic("helloActiveMQSpringTopic");
        DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
        dmlc.setConnectionFactory(cachingConnectionFactory());
        dmlc.setDestination(topic);
        dmlc.setMessageListener(new TopicListener());
        return dmlc;
    }

    @Bean("jmsQueueTemplate")
    public JmsTemplate jmsQueueTemplate(){
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(cachingConnectionFactory());
        return jmsTemplate;

    }

    @Bean("jmsTopicTemplate")
    public JmsTemplate jmsTopicTemplate(){
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(cachingConnectionFactory());
        jmsTemplate.setPubSubDomain(true);
        return jmsTemplate;

    }
}

